/*
 *  linux/kernel/system_call.s
 *
 *  (C) 1991  Linus Torvalds
 */

/*
 *  system_call.s  contains the system-call low-level handling routines.
 * This also contains the timer-interrupt handler, as some of the code is
 * the same. The hd- and flopppy-interrupts are also here.
 *
 * NOTE: This code handles signal-recognition, which happens every time
 * after a timer-interrupt and after each system call. Ordinary interrupts
 * don't handle signal-recognition, as that would clutter them up totally
 * unnecessarily.
 *
 * Stack layout in 'ret_from_system_call':
 *
 *	 0(%esp) - %eax
 *	 4(%esp) - %ebx
 *	 8(%esp) - %ecx
 *	 C(%esp) - %edx
 *	10(%esp) - %fs
 *	14(%esp) - %es
 *	18(%esp) - %ds
 *	1C(%esp) - %eip
 *	20(%esp) - %cs
 *	24(%esp) - %eflags
 *	28(%esp) - %oldesp
 *	2C(%esp) - %oldss
 */

SIG_CHLD	= 17

EAX		= 0x00
EBX		= 0x04
ECX		= 0x08
EDX		= 0x0C
FS		= 0x10
ES		= 0x14
DS		= 0x18
EIP		= 0x1C
CS		= 0x20
EFLAGS		= 0x24
OLDESP		= 0x28
OLDSS		= 0x2C

state	= 0		# these are offsets into the task-struct.
counter	= 4
priority = 8
signal	= 12
sigaction = 16		# MUST be 16 (=len of sigaction)
blocked = (33*16)

# offsets within sigaction
sa_handler = 0
sa_mask = 4
sa_flags = 8
sa_restorer = 12

nr_system_calls = 74

/*
 * Ok, I get parallel printer interrupts while using the floppy for some
 * strange reason. Urgel. Now I just ignore them.
 */
.globl system_call,sys_fork,timer_interrupt,sys_execve
.globl hd_interrupt,floppy_interrupt,parallel_interrupt
.globl device_not_available, coprocessor_error

.align 2
bad_sys_call:
	movl $-1,%eax
	iret
.align 2
reschedule:
	pushl $ret_from_sys_call
	jmp schedule
.align 2
# int $0x80 触发系统调用中断时，根据存储在eax寄存器中的调用号，调用中断处理函数
# 参考链接：https://www.cnblogs.com/ithepug/p/14456526.html
# 中断 是硬件提供的进入内核的唯一方法， int 指令使 CS 中的 CPL 改成 0，可以"进入内核"
system_call:
	# 判断是否超出系统调用号范围，超出范围后直接退出系统调用
	cmpl $nr_system_calls-1,%eax
	ja bad_sys_call
	# 在内核堆栈中压入需要保护的寄存器
	push %ds   # 调用者保护寄存器：ds、es、fs。因为后续要修改这些寄存器的值
	push %es
	push %fs
	# 系统调用采用寄存器传参：压入3个系统调用处理函数参数(系统调用最多支持3个参数的原因)
	pushl %edx
	pushl %ecx		# push %ebx,%ecx,%edx as parameters
	pushl %ebx		# to the system call
	# 设置段选择符
	movl $0x10,%edx		# set up ds,es to kernel space（内核数据段）
	mov %dx,%ds
	mov %dx,%es
	movl $0x17,%edx		# fs points to local data space（用户数据段、局部数据段）
	mov %dx,%fs
	# 调用系统调用处理函数
	call *sys_call_table(,%eax,4)  # sys_call_table + 4*eax 处内存单元的值为 第eax号的系统调用函数指针
	# eax为返回值，将返回值压栈
	pushl %eax
	# 将当前进程（系统调用发起者）的task结构体指针传送给eax
	movl current,%eax
	# 如果当前进程时间片结束，或者处于非可运行状态，则切换进程。否则进行信号预处理
	cmpl $0,state(%eax)		# state 。state(%eax) 为：“eax + state” 地址处解引用的值
		# ①如果current->state 不为0，则jmp reschedule
	jne reschedule
	cmpl $0,counter(%eax)		# counter
		# ②如果current->counter 为0，则jmp reschedule
	je reschedule
# 系统调用完成后的跳转地址，执行信号预处理
ret_from_sys_call:
	movl current,%eax		# task[0] cannot have signals
	cmpl task,%eax
	# 如果current为task[0]，iret返回
	je 3f
	cmpw $0x0f,CS(%esp)		# was old code segment supervisor ?
	# 如果old代码段不是用户态CS，iret返回
	jne 3f
	cmpw $0x17,OLDSS(%esp)		# was old stack segment = 0x17 ?
	# 如果old堆栈段不是用户态SS，iret返回
	jne 3f
	# (当前进程的)信号位图：需要处理的信号
	movl signal(%eax),%ebx
	# 信号屏蔽位图：表示不接受的信号
	movl blocked(%eax),%ecx
	# 对屏蔽位图取反后，再进行与操作，实现过滤屏蔽信号
	notl %ecx
	andl %ebx,%ecx  # 此时ecx为真正需要处理的信号位图
	bsfl %ecx,%ecx # 此时，ecx中为从位0开始寻找到的第一个待处理信号的位号(索引值)
	je 3f
	# 如果过滤屏蔽信号后，仍有需要处理的信号，则对最低位的信号进行处理
	btrl %ecx,%ebx #将信号位图待处理的信号位复位
	movl %ebx,signal(%eax)
	# 将 信号序号+1，作为信号编号值（因为从1开始编号）压栈，作为do_signal的参数
	incl %ecx
	pushl %ecx
	# 信号处理
	call do_signal
	# 删除栈上的do_signal参数(signr)
	popl %eax
	# 恢复调用系统调用处理函数之前保存的寄存器
3:	popl %eax
	popl %ebx
	popl %ecx
	popl %edx
	pop %fs
	pop %es
	pop %ds
	iret # 开始执行信号处理程序(如果有的信号需要处理)或系统调用前的用户态程序

.align 2
coprocessor_error:
	push %ds
	push %es
	push %fs
	pushl %edx
	pushl %ecx
	pushl %ebx
	pushl %eax
	movl $0x10,%eax
	mov %ax,%ds
	mov %ax,%es
	movl $0x17,%eax
	mov %ax,%fs
	pushl $ret_from_sys_call
	jmp math_error

.align 2
device_not_available:
	push %ds
	push %es
	push %fs
	pushl %edx
	pushl %ecx
	pushl %ebx
	pushl %eax
	# 设置ds、es为内核数据段
	movl $0x10,%eax
	mov %ax,%ds
	mov %ax,%es
	# 设置fs为局部数据段
	movl $0x17,%eax
	mov %ax,%fs
	pushl $ret_from_sys_call
	clts				# clear TS so that we can use math
	movl %cr0,%eax
	testl $0x4,%eax			# EM (math emulation bit)
	je math_state_restore
	# 若 EM标志是置位的，则去执行数学仿真程序 math emulate()。
	pushl %ebp
	pushl %esi
	pushl %edi
	call math_emulate
	# 因为压入栈的3个参数未使用，所以需要手动弹出
	popl %edi
	popl %esi
	popl %ebp
	ret

.align 2
# 时钟中断（或称 定时器中断）
timer_interrupt:
	push %ds		# save ds,es and put kernel data space
	push %es		# into them. %fs is used by _system_call
	push %fs
	pushl %edx		# we save %eax,%ecx,%edx as gcc doesn't
	pushl %ecx		# save those across function calls. %ebx
	pushl %ebx		# is saved as we use that in ret_sys_call
	pushl %eax
	movl $0x10,%eax
	mov %ax,%ds
	mov %ax,%es
	movl $0x17,%eax
	mov %ax,%fs
	incl jiffies  # jiffies累加1
	# 由于初始化中断控制芯片时没有采用自动 EOI，所以这里需要发指令结束该硬件中断。
	movb $0x20,%al		# EOI to interrupt controller #1
	outb %al,$0x20
	# 下面从堆栈中取出时钟中断发生时正被执行的代码选择符（CS段寄存器值）中的当前特权级别(0或3）并压入堆栈，作为 do_timer 的参数。
	movl CS(%esp),%eax
	andl $3,%eax		# %eax is CPL (0 or 3, 0=supervisor)
	pushl %eax
	# do_timer(）函数执行任务切换、计时等工作，在 kernel/sched.c, 305行实现。
	call do_timer		# 'do_timer(long CPL)' does everything from
	# 忽略返回值
	addl $4,%esp		# task switching to accounting ...
	jmp ret_from_sys_call

.align 2
sys_execve:
	# eax 指向堆栈中保存用户程序 eip 指针处（EIP+%esp）
	lea EIP(%esp),%eax
	pushl %eax
	call do_execve
	# 丢弃调用时压入栈的EIP 值
	addl $4,%esp
	ret

.align 2
sys_fork:
	call find_empty_process # C函数（find_empty_process）执行后，（编译器）会将函数返回值赋值到eax寄存器中
	testl %eax,%eax
	# 在 eax 中返回进程号 pid。若返回负数则退出。
	js 1f
	push %gs
	pushl %esi
	pushl %edi
	pushl %ebp
	pushl %eax # 入参：task nr 任务号
	call copy_process
	# 丢弃这里所有压栈内容
	addl $20,%esp
1:	ret

hd_interrupt:
	pushl %eax
	pushl %ecx
	pushl %edx
	push %ds
	push %es
	push %fs
	movl $0x10,%eax
	mov %ax,%ds
	mov %ax,%es
	movl $0x17,%eax
	mov %ax,%fs
	movb $0x20,%al
	outb %al,$0xA0		# EOI to interrupt controller #1
	# 延时
	jmp 1f			# give port chance to breathe
1:	jmp 1f
1:	xorl %edx,%edx
	xchgl do_hd,%edx  # do_hd是一个指针函数变量（全局变量）
	testl %edx,%edx
	# 测试do_hd函数指针是否为 Null
	jne 1f
	# 若为Null，则将待调用函数设置为unexpected_hd_interrupt
	movl $unexpected_hd_interrupt,%edx  # unexpected_hd_interrupt是一个函数，需要使用$符号对其取地址
1:	outb %al,$0x20
	call *%edx		# "interesting" way of handling intr.
	pop %fs
	pop %es
	pop %ds
	popl %edx
	popl %ecx
	popl %eax
	iret

# 软盘中断处理函数（软盘控制器发出中断时，会触发此函数执行）
floppy_interrupt:
	pushl %eax
	pushl %ecx
	pushl %edx
	push %ds
	push %es
	push %fs
	movl $0x10,%eax
	mov %ax,%ds
	mov %ax,%es
	movl $0x17,%eax
	mov %ax,%fs
	movb $0x20,%al
	outb %al,$0x20		# EOI to interrupt controller #1
	xorl %eax,%eax
	xchgl do_floppy,%eax
	testl %eax,%eax  # 判断do_floppy的地址是否为NULL
	jne 1f
	movl $unexpected_floppy_interrupt,%eax
1:	call *%eax		# "interesting" way of handling intr.
	pop %fs
	pop %es
	pop %ds
	popl %edx
	popl %ecx
	popl %eax
	iret

parallel_interrupt:
	pushl %eax
	movb $0x20,%al
	outb %al,$0x20
	popl %eax
	iret
